如何为降序值编写Python排序键函数

您所在的位置:网站首页 sort values降序 如何为降序值编写Python排序键函数

如何为降序值编写Python排序键函数

#如何为降序值编写Python排序键函数| 来源: 网络整理| 查看: 265

缓慢但优雅的方法是创建一个具有相反顺序的值包装器:

from functools import total_ordering@total_orderingclass ReversedOrder: def __init__(self, value): self.value = value def __eq__(self, other): return other.value == self.value def __lt__(self, other): return other.value

如果没有functools.total_ordering,则必须实施所有6个比较,例如:

import operatorclass ReversedOrder: def __init__(self, value): self.value = valuefor x in ['__lt__', '__le__', '__eq__', '__ne__', '__ge__', '__gt__']: op = getattr(operator, x) setattr(ReversedOrder, x, lambda self, other, op=op: op(other.value, self.value))



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3